import Konva from "konva";
import { Draw } from "./Draw";
import { IColorMatch } from "../Interface/ColorMatch";
import { KONVA_GRAPH_NAME, KONVA_LINE_NAME } from "../Config";
import { COLOR_MATCH_ARRAY } from "../Config/color-match-array";

/**
 * 系统配色方案：
 *  支持 自定义、图片生成、选色生成
 */
export class ColorScheme {
  private draw: Draw;
  private colorMatch: IColorMatch = COLOR_MATCH_ARRAY.ColorMatch1; // 默认第一个配色方案

  constructor(draw: Draw) {
    this.draw = draw;
  }

  // 设置配色方案 - 支持自定义 或者系统内置方案
  public setColorMatch(payload: IColorMatch | string) {
    this.colorMatch =
      typeof payload === "string" ? COLOR_MATCH_ARRAY[payload] : payload;

    /**
     * 循环所有的 baseGroup
     *  下列基础图形无法直接进行配色变化，需要循环 通过 attrs 设置，这些图形不是通过 Konva Shape 绘制的，无法render时重新绘制
     *  Rect
     *  Ring
     *  Star
     */
    const baseShape = [
      "Rect",
      "Ring",
      "Star",
      "Text",
      "Ellipse",
      "Circle",
      "Line",
    ];

    const setLayerColorMatch = (layer: Konva.Layer) => {
      // 处理 Group 的换肤
      layer.find("Group").forEach((group) => {
        // 获取图形类型
        if (group.name() !== KONVA_GRAPH_NAME) return;

        const shapeList = (<Konva.Group>group).children;
        shapeList.forEach((shape) => {
          if (!baseShape.includes(shape.className)) return;
          if (shape.className === "Text")
            return (shape.attrs.fill = this.colorMatch.nodeTextColor);

          shape.attrs.fill = this.colorMatch.nodeFillColor;
          shape.attrs.stroke = this.colorMatch.nodeStrokeColor;
        });
      });

      // 处理 Line 的换肤
      layer.find(`.${KONVA_LINE_NAME}`).forEach((line) => {
        line.attrs.stroke = this.colorMatch.nodeFillColor;
        line.attrs.fill = this.colorMatch.nodeFillColor;
      });

      // 处理 Line Control 的换肤
      layer.find(".line-control").forEach((control) => {
        control.attrs.stroke = this.colorMatch.transformerColor;
        control.attrs.fill = this.colorMatch.transformerColor;
      });
    };

    // 这个是循环设置LayerList
    const layerList = this.draw.getLayerManager().getLayerList();
    layerList.forEach((layer) => setLayerColorMatch(layer));
    // 这个是设置当前 页面的视图 ，不然缩略图变化，页面并没有变化
    setLayerColorMatch(this.draw.getLayer()!);

    // 单独处理背景
    const command = this.draw.getCommand();
    command.executeSetBackground({
      bgType: "fill",
      fill: this.colorMatch.slideFillColor,
      stroke: this.colorMatch.slideStrokeColor,
      global: true,
    });

    // 单独处理 形变节点
    this.draw
      .getStage()
      .find("Transformer")
      .forEach((tr) => {
        tr.setAttrs({
          anchorStroke: this.colorMatch.transformerColor,
          anchorFill: this.colorMatch.transformerColor,
          borderStroke: this.colorMatch.transformerColor,
        });
      });

    this.draw.render();
  }

  // 获取配色方案
  public getColorMatch = () => this.colorMatch;
}
